﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using System.Net;
using System.IO;
using Newtonsoft.Json.Linq;
using System.Diagnostics;
using System.Web;


namespace JbolanoPocketSync
{
    class oAuth
    {
        string _code;
        string _access_token;

        #region "Properties"
        public string consumer_key
        {
            get
            {
                return "11126-2268dc9986eab9b9049c2f30";
                //Consumer KEY. You can get you own from https://getpocket.com/developer/
            }
            
        }
        public string redirect_uri
        {
            get;
            set;
        }
        public string state
        {
            get;
            set;
        }
        public string code
        {
            get{return _code; }
            set { _code = value; }
        }
        public string detailType
        {
            get;
            set;
        }
        public string access_token
        {
            get { return _access_token;  }
            set { _access_token = value; }
        }

        public string tag
        {
            get;
            set;
        }
        private List<Action> _actions = new List<Action>();
        public List<Action> actions
        {
            get { return _actions; }
            set { _actions = value; }
        }

        public string item_id
        {
            get;
            set;
        }

        public string status
        {
            get;
            set;
        }
        #endregion

        [JsonConstructor]
        public oAuth(bool init = false)
        {
            if (init)
            {
                GetAuthorization();
            }
        }

        public oAuth(string code, string access_token)
        {
            _access_token = access_token;
            _code = code;
        }
        
        public void GetAuthorization(){
           
            string _parameter = "jbolano:authorizationFinished"; //?? Obligatorio en la autorización.
            string _urlRedirect = "http://winpocket.codeplex.com";

            oAuth oa = new oAuth();

            oa.redirect_uri = _parameter;
            oa = Petition("https://getpocket.com/v3/oauth/request", oa);
            _code = oa.code;

            //paso... AUTORIZACION, por navegador.
            string _url = string.Format(@"https://getpocket.com/auth/authorize?request_token={0}&redirect_uri={1}", _code, _urlRedirect);
            
            ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo();
            info.FileName = _url;
            info.CreateNoWindow = false;
            Process process = new Process();
            process.StartInfo = info;
            process.Start();


            System.Threading.Thread.Sleep(10000);


            oa = Petition("https://getpocket.com/v3/oauth/authorize", oa);
            _access_token = oa.access_token;
        }

        private oAuth Petition(string url, oAuth oa)
        {
            string json = JsonConvert.SerializeObject(oa);

            var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Method = "POST";
            StreamWriter requestWriter;
            using (requestWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                requestWriter.Write(json);
            }

            string datos = string.Empty;
            HttpWebResponse resp = (HttpWebResponse)httpWebRequest.GetResponse();
            Stream resStream = resp.GetResponseStream();
            using (StreamReader reader = new StreamReader(resStream))
            {
                datos = reader.ReadToEnd();
            }
            

            oAuth response = JsonConvert.DeserializeObject<oAuth>(ParseResponse(datos));
            return response;

        }

        private string ParseResponse(string response)
        {
            string parser = string.Empty;
            if (response.Contains("&"))
            {
                response = response.Split(new Char[] { '&' })[0];
            }
            parser = "{'" + response.Replace("=", "':'") + "'}";
            
            return parser;
        }

        public Articles Operation(string url, oAuth oa)
        {
            //peticion
            string json = JsonConvert.SerializeObject(oa);

            var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Method = "POST";
            StreamWriter requestWriter;
            using (requestWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                requestWriter.Write(json);
            }

            string response;
            HttpWebResponse resp = (HttpWebResponse)httpWebRequest.GetResponse();
            Stream resStream = resp.GetResponseStream();
            StreamReader reader = new StreamReader(resStream);
            response = reader.ReadToEnd();

            Articles arts = JsonConvert.DeserializeObject<Articles>(response);
            return arts;
        }

        public oAuth Archive(string url, oAuth oa)
        {
            oa.status = "1";
            string response = JsonConvert.SerializeObject(oa);

            if (oa.actions.Count > 0)
            {
                string request = "actions=%5B";
                foreach (Action a in oa.actions)
                {
                    request += HttpUtility.UrlEncode("{\"action\":\"archive\",\"item_id\":" + a.item_id + "},", Encoding.UTF8);
                }
                request = request.Remove(request.Length - 3, 3);
                request += "%5D&access_token=" + oa.access_token + "&consumer_key=" + oa.consumer_key + "";

                request = url + "?" + request;


                WebClient wc = new WebClient();
                response = wc.DownloadString(request);

            }

            oAuth arts = JsonConvert.DeserializeObject<oAuth>(response);
            return arts;
        }
    }

}
